package cn.lds.j367.ssm.service.impl;

import cn.lds.j367.ssm.entity.Authority;
import cn.lds.j367.ssm.entity.DevUser;
import cn.lds.j367.ssm.mapper.UserMapper;
import cn.lds.j367.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        DevUser devUser = userMapper.selectUserByUsername(s);

        Set<Authority> authoritySet = new HashSet<>();

        devUser.getRoleList().forEach(role -> {
            role.getAuthorityList().forEach(authority -> {
                authoritySet.add(authority);
            });
        });


        User loginUser = new User(devUser.getUsername(), "{noop}" + devUser.getPassword(), true,true,true,devUser.getIsDelete() == 0?true:false,this.getAuthority(authoritySet));

        return loginUser;
    }

    public List<SimpleGrantedAuthority> getAuthority(Set<Authority> authoritySet){
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
//        simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        authoritySet.forEach(authority -> {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + authority.getAuthorityName()));
        });
        return simpleGrantedAuthorities;
    }
}
